//
//  LXTextView.m
//  LvXi_newVersion
//
//  Created by 王敏 on 16/9/5.
//  Copyright © 2016年 SJT. All rights reserved.
//

#import "LXTextView.h"

@interface LXTextView()<UITextViewDelegate>

@property(nonatomic,strong)UILabel * placeholderLabel;


@end

@implementation LXTextView

-(id)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
        self.placeholderLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        self.placeholderLabel.textColor = HexColor(@"#EEEEEE");
        self.delegate = self;
        [self addSubview:self.placeholderLabel];
        
        self.textCountLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        self.textCountLabel.textAlignment = NSTextAlignmentRight;
        self.textCountLabel.font = [UIFont systemFontOfSize:11];
        [self addSubview:self.textCountLabel];
    }
    return self;
}
-(void)setFont:(UIFont *)font{
    self.placeholderLabel.font = font;
    [super setFont:font];
}
-(void)setPlaceholder:(NSString *)placeholder{
    _placeholder = placeholder;
    self.placeholderLabel.text = _placeholder;
    [self setNeedsLayout];
}

- (void)setPlaceHolderColor:(UIColor *)color
{
    self.placeholderLabel.textColor = color;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    self.placeholderLabel.x = globalMargin;
    self.placeholderLabel.y = globalMargin;
    self.placeholderLabel.numberOfLines = 0;
    self.placeholderLabel.size = [self.placeholderLabel.text sizeInAre:self.size font:self.placeholderLabel.font];
    
    self.textCountLabel.x = globalMargin;
    self.textCountLabel.y = self.height - 12-globalMargin;
    self.textCountLabel.height = 12;
    self.textCountLabel.width = self.width - 2*globalMargin;
    self.textCountLabel.text = [NSString stringWithFormat:@"0/500"];

}


- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    
    return YES;
}

-(void)textViewDidChange:(UITextView *)textView{
    self.placeholderLabel.hidden = self.hasText;
    self.textCountLabel.text = [NSString stringWithFormat:@"%ld/500",textView.text.length];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if(range.location>=500){
        return NO;
    }else{
//        self.textCountLabel.text = [NSString stringWithFormat:@"%ld/500",range.location+1];
        return YES;
    }
}
@end
